<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/18
 * Time: 17:19
 */

namespace app\admin\model;
use think\Exception;
use think\Model;
class User extends Model
{
    protected $autoWriteTimestamp=true;

    protected $createTime       ='create_time';
    protected $updateTime       ='edit_time';

    public function addDb($data,$allow_fields,$where=[]){
       try{
           $allow_fields    =   empty($allow_fields)?true:$allow_fields;
           if(empty($where)){
               $count           =   $this->where(['name'=>$data['name']])->count();
               if($count>0){throw new Exception('抱歉该用户已经注册请！');}
               $result          =   $this->allowField($allow_fields)->save($data);
               if($result===false){throw new Exception('抱歉祖册失败！');}
               return $result;
           }
           $result              =$this->allowField($allow_fields)->save($data,$where);
           if(false===$result){throw new Exception('抱歉数据修改失败');}
       }catch (Exception $exception){$this->error=$exception->getMessage(); return false;}
    }

    public function lists($where,$allow_field,$order,$page){
        try{
            if(empty($order)){$order=true;}
            $list   =   $this->where($where)->order(['id'=>'DESC'])->field($allow_field)->paginate($page,false);
            $list   =   $list->toArray();
            if(empty($list)){throw new Exception('抱歉小惠没找到没有任何您需要的数据！');}
            return $list;
        }catch (Exception $exception){$this->error=$exception->getMessage();return false;}

    }

    public function read($id,$allow_fields){
        try{
            $allow_fields    =   empty($allow_fields)?true:$allow_fields;
            $data         =   $this->where(['id'=>['eq',$id]])->field($allow_fields)->find();
            if(empty($data)){throw new Exception('抱歉小惠没找到没有任何您需要的数据！');}
            return $data->toArray();
        }catch (Exception $exception){$this->error=$exception->getMessage();return false;}
    }

    /**
     * @param $param -| 检查当前登录
     */
    public function check_login($param){
       try{
           $name            = $password='';extract($param);
           $user            = $this->where(function($query)use($name){
               $query->where(['name'=>['eq',$name]]);
           })->field('password,id,slot,nickname')->find();
           //  判断是否为空
           if(empty($user)){throw new Exception('抱歉用户不存在！');}
           if(strcmp(md5($password.$user->slot),$user->password)!==0){throw new Exception('抱歉用户或密码错误');}
           return array_combine(['id','nickname'],[$user->id,$user->nickname]);
       }catch (Exception $exception){$this->error=$exception->getMessage();return false;}
    }
}